<template>
  <div class="user-table-page">
    <el-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center">
          <span>用户管理</span>
          <div style="display: flex; align-items: center; gap: 8px">
            <el-button @click="refreshCurrentMode" :loading="loading">刷新</el-button>
            <el-button v-if="!postMode" @click="openConditionDialog">条件查询</el-button>
            <el-button v-if="postMode" @click="switchToGet">重置为全部</el-button>
          </div>
        </div>
      </template>
      <el-table :data="userList" v-loading="loading" style="width: 100%; margin-bottom: 16px">
        <el-table-column prop="username" label="用户名" width="90" />
        <el-table-column prop="nickname" label="昵称" width="90" />
        <el-table-column prop="name" label="姓名" width="80" />
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="scope">
            <span>{{ scope.row.sex === 1 ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="eduBack" label="学历" width="100" />
        <el-table-column prop="salaryWishK" label="期望薪资" width="90" />
        <el-table-column prop="address" label="地址" width="180" />
        <el-table-column prop="hasExperience" label="有无经验" width="100">
          <template #default="scope">
            <span>{{ scope.row.hasExperience === 1 ? '有' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="introduction" label="简介" width="140"   show-overflow-tooltip> 
        </el-table-column>
        <el-table-column fixed="right"  label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :loading="deleteLoadingId === scope.row.username"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

  </el-card>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px">
  <!-- 左侧分页控件 -->
  <el-pagination
    background
    layout="prev, pager, next, jumper, ->, total"
    :total="total"
    :page-size="pageSize"
    :current-page="pageNum"
    @current-change="handlePageChange"
  />

  <!-- 右侧跳转功能 -->
  <div style="display: flex; align-items: center; gap: 8px">
    <div style="display: flex; align-items: center; gap: 4px">
      <!-- <span style="font-size: 12px">每页条数：</span> -->
      <span style="display: flex; align-items: center; gap: 4px">每页条数：</span>
      <el-input-number
        v-model="inputPageSize"
        :min="1"
        :max="100"
        size="small"
        style="width: 100px"
        :step="1"
        placeholder="每页条数"
      />
    </div>
    <!-- <el-button size="small" @click="applyPageInput">跳转分页</el-button> -->
    <el-button  @click="applyPageInput">跳转分页</el-button>
  </div>
</div>


    <!-- 条件查询弹窗 -->
    <el-dialog title="条件查询" v-model="conditionDialogVisible" width="500px">
      <el-form :model="conditionForm" label-width="90px">
        <el-form-item label="用户名">
          <el-input v-model="conditionForm.username" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="conditionForm.nickname" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="conditionForm.name" clearable />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="conditionForm.age" :min="0" :max="150" clearable />
        </el-form-item>
        <el-form-item label="有无经验">
          <el-select v-model="conditionForm.hasExperience" clearable placeholder="请选择">
            <el-option label="有" :value="1" />
            <el-option label="无" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="conditionForm.sex" clearable placeholder="请选择">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="conditionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="applyCondition">查询</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog
      :title="dialogMode === 'add' ? '添加用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" label-width="90px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="dialogMode === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogMode === 'add'">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历" prop="eduBack">
          <el-input v-model="form.eduBack" />
        </el-form-item>
        <el-form-item label="期望薪资" prop="salaryWishK">
          <el-input-number v-model="form.salaryWishK" :min="0" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="有无经验" prop="hasExperience">
          <el-select v-model="form.hasExperience">
            <el-option label="有" :value="1" />
            <el-option label="无" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="dialogLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getUserList, addUser, updateUser, deleteUser, getAllUsers } from '@/api/user'
import { showCustomMessage } from '@/utils/message'
import type { FormInstance, FormRules } from 'element-plus'

const userList = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const inputPageNum = ref(1)
const inputPageSize = ref(10)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const dialogLoading = ref(false)
const deleteLoadingId = ref<string | null>(null)
const formRef = ref<FormInstance>()
const postMode = ref(false) // false: GET分页所有，true: GET分页条件
const conditionDialogVisible = ref(false)
const conditionForm: Record<string, any> = reactive({
  username: '',
  nickname: '',
  name: '',
  age: undefined,
  hasExperience: undefined,
  sex: undefined,
})
let lastCondition: Record<string, any> = {} // 记录上次查询条件

const form = reactive({
  username: '',
  nickname: '',
  password: '',
  name: '',
  phone: '',
  email: '',
  age: 18,
  sex: 1,
  eduBack: '',
  salaryWishK: 0,
  address: '',
  introduction: '',
  hasExperience: 0,
})

const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  eduBack: [{ required: true, message: '请输入学历', trigger: 'blur' }],
  salaryWishK: [{ required: true, message: '请输入期望薪资', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  hasExperience: [{ required: true, message: '请选择有无经验', trigger: 'change' }],
}

// GET分页获取所有用户
const fetchUsersGet = async () => {
  loading.value = true
  try {
    const response = await getAllUsers({ pageNum: pageNum.value, pageSize: pageSize.value })
    userList.value = response.data.list || []
    total.value = response.data.total || response.data.length || 0
    postMode.value = false
    showCustomMessage('GET分页获取所有用户成功', 'success')
  } catch (error: any) {
    showCustomMessage('GET分页获取所有用户失败: ' + error.message, 'error')
  } finally {
    loading.value = false
  }
}

// GET分页条件查询用户
const fetchUsersPost = async (condition: Record<string, any> = {}) => {
  loading.value = true
  try {
    // 只传递有值的条件
    const params: Record<string, any> = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...condition,
    }
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === undefined || params[key] === null) {
        delete params[key]
      }
    })
    const response = await getUserList(params)
    userList.value = response.data.list || []
    total.value = response.data.total || response.data.length || 0
    postMode.value = true
    showCustomMessage('GET分页条件查询成功', 'success')
  } catch (error: any) {
    showCustomMessage('GET分页条件查询失败: ' + error.message, 'error')
  } finally {
    loading.value = false
  }
}

const openConditionDialog = () => {
  conditionDialogVisible.value = true
}

const applyCondition = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  // 记录本次条件
  lastCondition = { ...conditionForm }
  conditionDialogVisible.value = false
  fetchUsersPost(lastCondition)
}

const switchToPost = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  openConditionDialog()
}

const switchToGet = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  // 清空条件
  Object.keys(conditionForm).forEach((key) => (conditionForm[key] = undefined))
  lastCondition = {}
  fetchUsersGet()
}

const refreshCurrentMode = () => {
  if (postMode.value) {
    fetchUsersPost(lastCondition)
  } else {
    fetchUsersGet()
  }
}

const handlePageChange = (val: number) => {
  pageNum.value = val
  inputPageNum.value = val
  refreshCurrentMode()
}

const applyPageInput = () => {
  if (inputPageNum.value < 1) inputPageNum.value = 1
  if (inputPageSize.value < 1) inputPageSize.value = 1
  pageNum.value = inputPageNum.value
  pageSize.value = inputPageSize.value
  refreshCurrentMode()
}

const openAddDialog = () => {
  dialogMode.value = 'add'
  Object.assign(form, {
    username: '',
    nickname: '',
    password: '',
    name: '',
    phone: '',
    email: '',
    age: 18,
    sex: 1,
    eduBack: '',
    salaryWishK: 0,
    address: '',
    introduction: '',
    hasExperience: 0,
  })
  dialogVisible.value = true
}

const openEditDialog = (row: any) => {
  dialogMode.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    dialogLoading.value = true
    try {
      if (dialogMode.value === 'add') {
        await addUser(form)
        showCustomMessage('添加用户成功', 'success')
      } else {
        await updateUser(form)
        showCustomMessage('编辑用户成功', 'success')
      }
      dialogVisible.value = false
      refreshCurrentMode()
    } catch (error: any) {
      showCustomMessage(
        (dialogMode.value === 'add' ? '添加' : '编辑') + '用户失败: ' + error.message,
        'error',
      )
    } finally {
      dialogLoading.value = false
    }
  })
}

const handleDelete = async (row: any) => {
  if (!row.username) return
  if (!confirm(`确定要删除用户 ${row.username} 吗？`)) return
  deleteLoadingId.value = row.username
  try {
    await deleteUser(row.username)
    showCustomMessage('删除用户成功', 'success')
    refreshCurrentMode()
  } catch (error: any) {
    showCustomMessage('删除用户失败: ' + error.message, 'error')
  } finally {
    deleteLoadingId.value = null
  }
}




onMounted(() => {
  fetchUsersGet()
})
</script>

<style scoped>
.user-table-page {
  padding: 20px;
}
</style>
